<template>
   
    <div class="head" style="margin-bottom: 10px;margin-top: 10px;">
        <el-button type="danger" @click="batchDel">批量删除</el-button>
        <el-input type="text" style="height: 30px;width:250px;margin-right: 900px;" 
        v-model="name" placeholder="请输入员工姓名">
        <template #prefix>
          <el-icon class="el-input__icon"><el-icon><Search /></el-icon></el-icon>
        </template>
     </el-input>
     <el-button type="primary" style="position: absolute;right:900px" @click="search">搜索</el-button>
     <el-button type="primary" @click="insertOne" style="position: absolute;right: 100px;">新增员工</el-button>
     <!-- <el-button type="primary">新增套餐分类</el-button> -->
    </div>
    
    <el-table :data="tableData" border style="width: 100%;height: 540px;" stripe 
     ref="multipleTableRef"
     @selection-change="handleSelectionChange">
     <el-table-column type="selection" width="55" />
     <el-table-column prop="img" label="员工头像" width="180" align="center">
        <template #default="scope">
        <div class="demo-image__preview">
         <el-image
            style="width: 75px; height: 75px"
            :src="userImgUrl + scope.row.userImg"
            :zoom-rate="1.2"
            :max-scale="7"
            :min-scale="0.2"
            :preview-src-list="imgList"
            :initial-index="4"
            fit="cover"
            />
        </div>
        </template>
     </el-table-column>
     <el-table-column prop="name" label="员工姓名" width="100" />
     <el-table-column prop="username" label="账号" width="130" />
     <el-table-column prop="password" label="密码" />
     <el-table-column prop="phone" label="手机号" width="130"/>
     <el-table-column prop="updateTime" label="修改时间" width="120"/>
     <el-table-column prop="status" label="状态" width="70">
        <template #default="scope">
            <el-tag v-if="scope.row.status=='启用'" size="large"> {{ scope.row.status }}</el-tag>
            <el-tag type="danger" v-if="scope.row.status=='禁用'" size="large">{{ scope.row.status }}</el-tag>
        </template>
     </el-table-column>
     <el-table-column  label="操作" >
         <template #default="scope">
          <el-button type="primary" @click="updateOne(scope.$index,scope.row)">编辑</el-button>
          <el-button type="danger" @click="changeStatus(scope.$index,scope.row)" v-if="scope.row.status=='启用'">
            {{ scope.row.status=='启用'?'禁用':'启用' }}
          </el-button>
          <el-button type="success" @click="changeStatus(scope.$index,scope.row)" v-if="scope.row.status=='禁用'">
            {{ scope.row.status=='启用'?'禁用':'启用' }}
          </el-button>
          <el-button type="warning" @click="deleteOne(scope.$index,scope.row)">删除</el-button>
         </template>
     </el-table-column>
    </el-table>
 
 <!-- 分页组件 -->
<el-pagination background layout="prev, pager, next,sizes" :total="total" 
:page-sizes="[10, 15, 20, 25]"
  v-model:current-page="currentPage"
  v-model:page-size="pageSize"
  @size-change="handleSizeChange"
  @current-change="handleCurrentChange"/>
  
    <!-- 新增员工对话框 -->
    <el-dialog v-model="dialogFormVisible" :title="title">
     <el-form :model="form">
      <!-- 头像框 -->
      <el-upload
        class="avatar-uploader"
        :action="userImgUploadUrl"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
      >
        <img v-if="form.userImg" :src="form.userImg" class="avatar" style="width: 240px;height: 200px;margin-left: 200px;" />
        <el-icon v-else class="avatar-uploader-icon" style="width:240px;height: 200px;margin-left: 200px;
        border: 1px solid black;"><Plus /></el-icon>
      </el-upload>
      

       <el-form-item label="员工姓名" :label-width="formLabelWidth">
         <el-input v-model="form.name" autocomplete="off" placeholder="请输入员工姓名" />
       </el-form-item>
 
       <el-form-item label="员工账号" :label-width="formLabelWidth">
        <el-input v-model="form.username" autocomplete="off" placeholder="请输入员工账号" />
       </el-form-item>
 
       <el-form-item label="员工密码" :label-width="formLabelWidth">
         <el-input v-model="form.password" autocomplete="off" placeholder="请输入员工密码"/>
       </el-form-item>
       <el-form-item label="手机号" :label-width="formLabelWidth">
         <el-input v-model="form.phone" autocomplete="off" placeholder="请输入员工手机号"/>
       </el-form-item>
       <el-form-item label="状态(默认禁用)" :label-width="formLabelWidth">
        <el-switch
            v-model="form.status"
            class="ml-2"
            style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
        />
       </el-form-item>
       
 
     </el-form>
     <template #footer>
       <span class="dialog-footer">
         <el-button @click="quexiao">取消</el-button>
         <el-button type="primary" @click="addOne">
           确定
         </el-button>
       </span>
     </template>
   </el-dialog>

   <!-- 删除员工对话框 -->
   <el-dialog
    v-model="delDialogVisible"
    title="Warning"
    width="30%"
    align-center
  >
    <span>你确定要删除所选用户吗?</span>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="delDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="deleteYes">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>

 
 </template>
 
 <script setup lang="ts">
 
 import { ref,onMounted,watch } from 'vue'
 import { ElTable } from 'element-plus'
 import {ElMessage} from 'element-plus' 
 import  UserApi from '../api/user'
 //导入图片配置
 import { userImgUrl ,userImgUploadUrl} from '@/config/imgconfig'
 import type { UploadProps } from 'element-plus'
 import imgApi from  '@/api/imgApi'




 const currentPage = ref(1)
 const pageSize = ref(10)
 const total = ref(0)

 const handleSizeChange = (val: number) => {
    getUser()
 }
 const handleCurrentChange = (val: number) => {
    getUser()
 }


 onMounted(()=>{
    getUser()
 })

const tableData:any = ref([])
async function getUser() {
    
  
    const data = await UserApi.getUser(currentPage.value,pageSize.value)
  

    if(data.code == 200){
        tableData.value = data.data.list;
        total.value = data.data.total
    }
}


 //多选功能
 const multipleTableRef = ref<InstanceType<typeof ElTable>>()
 const multipleSelection = ref<[]>([])
 const toggleSelection = (rows?: []) => {
   if (rows) {
     rows.forEach((row) => {
    
       multipleTableRef.value!.toggleRowSelection(row,true)
     })
   } else {
     multipleTableRef.value!.clearSelection()
   }
 }
 const handleSelectionChange = (val:[]) => {
    multipleSelection.value = val
 }
 
 
 
 
 //新增或者修改的标题
 const title = ref('新增员工')
 
 
 //新增菜品对话框
 const dialogFormVisible = ref(false)
 const formLabelWidth = '140px'
 //员工表单
 const form = ref({
    userImg:'',
    name:'',
    username:'',
    password:'',
    phone:'',
    status:true
 })
 
 const insertOne=()=>{
   dialogFormVisible.value = true;
   title.value = '新增员工'
   form.value.userImg = ''
   //imageUrl.value = ''
   resetForm()
 }

//重置表单数据
const resetForm=()=>{  form.value.userImg ='', form.value.name='',form.value.username='', form.value.password='',form.value.phone='',
 form.value.status='启用'}
   
 const name = ref('') 
//搜索员工
async function search(){
   var data = await UserApi.getUserByName(currentPage.value, pageSize.value, name.value)
    if(data.code == 200){
       tableData.value = data.data.list
    }
   
   


}
    

 //新增员工
 const addOne=async ()=>{

   var user = {
      id:0,
      username:form.value.username,
      password:form.value.password,
      name:form.value.name,
      phone:form.value.phone,
      userImg:ImgName.value,
      status:''
   }
    //如果是新增
     if(title.value=='新增员工'){
        if(form.value.status==false){
           user.status = '禁用'
        }
        if(form.value.status==true){
            user.status = '启用'
        }

  
        const data = await UserApi.addUser(user)
        if(data.code === 200){
          //将图片清空，防止误删
          addMsg()
          ImgName.value = ''
          delFlag.value = 0
          //在执行一次查询
          getUser()
        }else{
           ElMessage({'message':data.data,"type":"error"})
           return;
        }
       
     }else{
        if(form.value.status==false){user.status = '禁用'}
        if(form.value.status==true){ user.status = '启用' }
        //修改
        //alert(itemIndex.value)
         user.id = tableData.value[itemIndex.value].id
        const data = await UserApi.updateUser(user)
        if(data.code === 200){
          //将图片清空，防止误删
          addMsg()
          ImgName.value = ''
          delFlag.value = 0
          //在执行一次查询
          getUser()
        }else{
           ElMessage({'message':data.data,"type":"error"})
           return;
        }
    
     }
     dialogFormVisible.value = false
     resetForm()
 }
 //取消新增
 const quexiao=async ()=>{
     console.log(ImgName.value);
     if(ImgName.value === ''||ImgName.value === null){
       dialogFormVisible.value = false
       resetForm()
       return;
     }
     //将图片删除了，防止服务器端堆积
        const data = await imgApi.deleteUserImg(ImgName.value)
     dialogFormVisible.value = false
     resetForm()
 }
 //删除
 //要删除的数据(表格的索引)临时先保存一下,也可以是修改
 const itemIndex = ref(0)



 //新增头像框
//const imageUrl = ref('')
 //编辑员工
 const updateOne=(index:number,row:any)=>{
      //imageUrl.value = userImgUrl+row.userImg
      title.value = '编辑员工'
      dialogFormVisible.value = true;
      form.value.userImg = userImgUrl + row.userImg;
      form.value.name = row.name;
      form.value.username = row.username;
      form.value.password = row.password;
      form.value.phone=row.phone;
      if(row.status=='启用'){
         form.value.status=true
      }else{
         form.value.status = false
      }
      
      itemIndex.value = index
 }
 

 //改变员工状态
 const changeStatus=async (index:number,row:any)=>{
     var id = tableData.value[index].id
    if(row.status=='启用'){
        const data = await UserApi.changeStatus(id,0);
        row.status = '禁用'
    }else{
        const data = await UserApi.changeStatus(id,1);
        row.status = '启用'
    }
    //修改完之后再查询一次
    getUser()
    changeMsg()
 }

 const delDialogVisible = ref(false)
 //用来保存待删除的索引数组
 const delIndexs = ref([0])
 //判断是单个删除还是批量删除(开始是单个删除)
 const delOneOrAll = ref(false)
 //删除单个用户
 const deleteOne=(index:number,row:any)=>{
   delDialogVisible.value = true
   delOneOrAll.value = false
   delIndexs.value[0] = tableData.value[index].id
 }
 //按下确定删除按钮
 const deleteYes=async ()=>{
     var ids: any[] = []
    if(delOneOrAll.value===false){
        ids = delIndexs.value
    }else{
        multipleSelection.value.forEach(item =>{
           ids.push(item.id)
        })
    }

    const data = await UserApi.deleteUser(ids)
    if(data.code===200){
       delDialogVisible.value = false
       deleteMsg()
       //在执行一遍查询操作
       getUser()
    }else{
      ElMessage({"message":data.data,"type":"warning"})
    }
 }

 //批量删除
 const batchDel=()=>{
   delDialogVisible.value = true
   delOneOrAll.value = true
 }




 const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
 
  // if(ImgName.value!=''||ImgName.value!=null){
  //      imgApi.deleteUserImg(ImgName.value)
  //    }
  if(delFlag.value===1){
    imgApi.deleteUserImg(ImgName.value)
    delFlag.value = 0
  }

  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('图片格式必须是jpg')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能大于2MB')
    return false
  }
  return true
}
//图片上传成功之后的操作
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  ImgName.value = response.data
  delFlag.value = 1
  //console.log(ImgName.value);
  form.value.userImg = URL.createObjectURL(uploadFile.raw!)
}

//给一个img用来缓存一下这个响应的图片名称
const ImgName = ref('')
const delFlag = ref(0)
//监听弹窗，一旦从有到无，就删除图片
watch(dialogFormVisible,(newValue,oldValue)=>{
  //console.log(newValue,oldValue);
  if(newValue == false && oldValue==true){
      if(delFlag.value===1){
          imgApi.deleteUserImg(ImgName.value)
      }
  }
})


 
 //消息提示
 const deleteMsg = () => {ElMessage({ message: '删除成功',type: 'success', })}
   
 const addMsg = () => { ElMessage({ message: '添加员工成功', type: 'success',  })}
  
 const changeMsg = () => {   ElMessage({message:'状态变更成功',type:'success'})}
    
 const searchMsg = () => {   ElMessage({message:'搜索接口未开发',type:'warning'})}
 
 
  
    
    
  
 
 
 
 
 
 
 </script>
 
 
 <style scoped lang="less">
  .head{
     float: right;
  }
 .el-input{
     width: 400px;
     height: 40px;
 }
 </style>